package com.hzcx.app.simplechat.ui.setting;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.base.BaseActivity;
import com.hzcx.app.simplechat.common.Common;
import com.hzcx.app.simplechat.ui.login.event.WxLoginSuccessEvent;
import com.hzcx.app.simplechat.ui.mine.EditUserInfoActivity;
import com.hzcx.app.simplechat.ui.mine.event.EditUserInfoSuccesEvent;
import com.hzcx.app.simplechat.ui.publicui.PublicConfirmDialog;
import com.hzcx.app.simplechat.ui.setting.contract.AccountContract;
import com.hzcx.app.simplechat.ui.setting.event.UpdatePhoneEvent;
import com.hzcx.app.simplechat.ui.setting.presenter.AccountPresenter;
import com.hzcx.app.simplechat.ui.user.bean.UserInfoBean;
import com.hzcx.app.simplechat.util.UserInfoUtil;
import com.hzcx.app.simplechat.util.app.AppHelper;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 账号与安全界面
 */
public class AccountActivity extends BaseActivity<AccountPresenter> implements AccountContract.View {
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_title_right)
    ImageView ivTitleRight;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.tv_id)
    TextView tvId;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_pwd)
    TextView tvPwd;
    @BindView(R.id.tv_tips)
    TextView tvTips;
    @BindView(R.id.tv_bind_wx)
    TextView tvBindWx;
    @BindView(R.id.tv_bind_qq)
    TextView tvBindQq;
    @BindView(R.id.tv_id_value)
    TextView tvIdValue;
    @BindView(R.id.tv_phone_value)
    TextView tvPhoneValue;
    @BindView(R.id.tv_wechat_state)
    TextView tvWechatState;
    @BindView(R.id.tv_pwd_state)
    TextView tvPwdState;

    private IWXAPI api;

    @Override
    public int getLayout() {
        return R.layout.activity_account;
    }

    @Override
    public void initPresenter() {
        mPresenter = new AccountPresenter();
    }

    @Override
    public void initView() {
        tvTitle.setText("账号与安全");

        tvId.setText(getResources().getString(R.string.app_name) + "号");
        tvPwd.setText(getResources().getString(R.string.app_name) + "密码");
        try {
            tvWechatState.setText(UserInfoUtil.getUserIsWechat() == 1 ? "已绑定" : "未绑定");
            tvPwdState.setText(UserInfoUtil.getUserInfo().getIs_password() == 1 ? "已设置" : "未设置");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void initData() {
        tvIdValue.setText(UserInfoUtil.getUserNumber());
        tvPhoneValue.setText(AppHelper.hidePhone(UserInfoUtil.getUserPhone()));
    }

    @OnClick({R.id.tv_id, R.id.tv_phone, R.id.tv_pwd, R.id.tv_bind_wx, R.id.tv_bind_qq})
    public void viewOnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_id: // 修改id号
                startActivity(new Intent(this, EditUserInfoActivity.class));
                break;

            case R.id.tv_phone: // 修改手机号
                startActivity(new Intent(this, MinePhoneActivity.class));
                break;

            case R.id.tv_pwd: // 修改密码
                startActivity(new Intent(this, UpdatePwdActivity.class));
                break;

            case R.id.tv_bind_wx: // 绑定微信
                if (UserInfoUtil.getUserIsWechat() == 1) {
                    showConfirmDialog(null, "解除绑定后，您将无法使用此 账号登录。确定解除绑定吗？", null,
                            () -> mPresenter.bindWechat(AccountActivity.this, null));
                } else {
                    wxLogin();
                }
                break;

            case R.id.tv_bind_qq: // 绑定QQ
                showConfirmDialog(null, "解除绑定后，您将无法使用此 账号登录。确定解除绑定吗？", null, new PublicConfirmDialog.OnPublicConfirmClickListener() {
                    @Override
                    public void publicConfirm() {

                    }
                });
                break;
        }
    }

    /**
     * 微信登录
     */
    private void wxLogin() {
        //通过WXAPIFactory工厂获取IWXApI的示例
        api = WXAPIFactory.createWXAPI(this, Common.WX_APP_ID, true);
        //将应用的appid注册到微信
        api.registerApp(Common.WX_APP_ID);
        SendAuth.Req req = new SendAuth.Req();
        //授权读取用户信息
        req.scope = "snsapi_userinfo";
        //自定义信息
        req.state = "wechat_sdk_demo_test";
        //向微信发送请求
        boolean isSend = api.sendReq(req);
        if (isSend) {
            showLoading();
        } else {
            showError("微信登录失败");
        }
    }

    /**
     * 微信调用成功
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void wxLoginSuccess(WxLoginSuccessEvent event) {
        hideLoading();
        if (!event.isSuccess()) {
            showError(event.getMsg());
            return;
        }
        LogUtils.d(TAG, event.getCode());
        mPresenter.bindWechat(this, event.getCode());
    }

    /**
     * 用户信息修改成功，刷新UI
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void editUserInfoSuccess(EditUserInfoSuccesEvent event) {
        tvIdValue.setText(UserInfoUtil.getUserNumber());
    }


    /**
     * 修改手机号成功
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updatePhoneSuccess(UpdatePhoneEvent event) {
        tvPhoneValue.setText(AppHelper.hidePhone(UserInfoUtil.getUserPhone()));
    }

    /**
     * 绑定或解绑微信
     */
    @Override
    public void bindSuccess() {
        UserInfoBean bean = UserInfoUtil.getUserInfo();
        if (bean == null) {
            return;
        }
        if (bean.getIs_wechat() == 1) {
            bean.setIs_wechat(0);
            tvWechatState.setText("未绑定");
        } else {
            bean.setIs_wechat(1);
            tvWechatState.setText("已绑定");
        }
        UserInfoUtil.saveUser(bean);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        UserInfoBean userInfoBean = UserInfoUtil.getUserInfo();
        if (userInfoBean == null) {
            tvPwdState.setText("未设置");
        } else {
            tvPwdState.setText(userInfoBean.getIs_password() == 1 ? "已设置" : "未设置");
        }
    }

}
